﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Sitefinity.Security;

namespace Migration.Classes
{
	public static class MigrationRoles
	{
		private static RoleManager m_RoleManager;

		static MigrationRoles()
		{
			m_RoleManager = RoleManager.GetManager(MigrationSettings.RolesProvider);
		}

		public static void CheckManagers()
		{
			if (m_RoleManager.Provider == null || MigrationSettings.ApplicationRestarted)
			{
				m_RoleManager = RoleManager.GetManager(MigrationSettings.RolesProvider);
			}
		}

		public static void ImportRoles(List<Telerik.Sitefinity.Services.Migration.MigrationRole> rolesContent)
		{
			CheckManagers();

			foreach (var roleContent in rolesContent)
			{
				var checkRole = m_RoleManager.GetRole(roleContent.Name);
				if (checkRole != null)
				{
					MigrationLogger.AppendLogMessage(String.Format("Skipping role \"<b>{0}</b>\", already exists.", roleContent.Name));
					MigrationLogger.AppendNewLine();
					continue;
				}

				try
				{
					m_RoleManager.CreateRole(roleContent.Name);
				}
				catch
				{
					MigrationLogger.AppendLogMessage(String.Format("Skipping role \"<b>{0}</b>\", already exists.", roleContent.Name));
					MigrationLogger.AppendNewLine();
					continue;
				}

				MigrationLogger.AppendLogMessage(String.Format("Added role \"<b>{0}</b>\".<br/>", roleContent.Name));
			}

			m_RoleManager.SaveChanges();
		}
	}
}
